import { View, Button, Picker, Text } from "@tarojs/components";
import { useEffect, useState, useRef } from "react";
import Taro from "@tarojs/taro";
import { TCreateRecord, TPlanMotion, TValue } from "@/types";
import "./index.less";
import { addRecords, getRecord, updateRecord } from "@/request";
import { PopupProvider } from "@/store/popup";
import MotionSelector from "../planadd/MotionSelector";
import BaseTrigger, {
  RadioTrigger,
  NumberTrigger,
} from "@/components/BaseTrigger";
import { getFormatDate, RecordWay } from "@/utils";
import MotionSets from "../planadd/MotionSets";

const RecordAdd = () => {
  // const textRef = useRef<HTMLTextAreaElement>(null);
  const actionRef = useRef<string>();
  const [data, setData] = useState<TCreateRecord>({
    date: getFormatDate(),
    takeTime: 0,
    unit: 0,
    sets: [[0, 10]],
    recordWay: 0,
    setsType: 0,
    motionId: "",
    name: "",
  });

  const handleChangeSelect = (name: string, value: TValue, index?: number) => {
    const newData = { ...data };

    switch (name) {
      case "recordWay":
        newData.sets = [[0, 10]];
        newData.takeTime = 0;
        newData[name] = value as number;
        break;
      case "sets":
        newData.sets[index] = value;
        break;
      case "addSet":
        newData.sets.splice(index + 1, 0, [0, 10]);
        break;
      case "delSet":
        newData.sets.splice(index, 1);
        break;
      default:
        newData[name] = value;
    }

    setData(newData);
  };

  // 提交表单
  const handleSubmit = async () => {
    let res;

    if (data.motionId === "") {
      Taro.showToast({
        title: "请选择动作",
        icon: "error",
      });
      return;
    }

    if (actionRef.current === "add") {
      const { date, ...rest } = data;
      res = await addRecords({
        date,
        records: [
          {
            ...rest,
            takeTime: rest.takeTime * 60,
          },
        ],
      });
    } else {
      const { name, ...rest } = data;
      res = await updateRecord(rest);
    }
    if (res) {
      Taro.navigateBack();
    }
  };

  const handleGetData = async (id: string) => {
    const res = await getRecord(id);
    setData(res);
  };

  useEffect(() => {
    const id = Taro.getCurrentInstance().router?.params?.id;
    if (id) {
      handleGetData(id);
    }
    Taro.setNavigationBarTitle({ title: id ? "编辑记录" : "添加记录" });
    actionRef.current = id ? "edit" : "add";
  }, []);

  const handleSelectMotion = (items: TPlanMotion[]) => {
    if (items.length > 0) {
      const item = items[0];
      setData({
        ...data,
        motionId: item.motionId,
        name: item.name,
      });
    }
  };

  return (
    <PopupProvider>
      <View className="record-add">
        <View className="form-card">
          <Picker
            mode="date"
            value={data.date}
            onChange={(e) => {
              handleChangeSelect("date", e.detail.value);
            }}
          >
            <BaseTrigger label="日期" value={data.date} />
          </Picker>
          <MotionSelector
            onSelect={handleSelectMotion}
            isMulti={false}
            trigger={<BaseTrigger label="动作" value={data.name} />}
          />

          <RadioTrigger
            label="记录方式"
            value={data.recordWay}
            options={RecordWay}
            onChange={(v) => {
              handleChangeSelect("recordWay", v);
            }}
          />
        </View>

        <View className="form-card">
          {data.recordWay === 1 ? (
            <NumberTrigger
              label="训练时间(分钟)"
              value={data.takeTime}
              onConfirm={(v) => {
                handleChangeSelect("takeTime", v);
              }}
            />
          ) : (
            <>
              <View className="form-item">
                <Text>训练组次</Text>
              </View>
              <MotionSets
                motion={data}
                onChange={handleChangeSelect}
                className="form-item-base"
                style={{ marginTop: 0 }}
              />
            </>
          )}
        </View>

        <Button onClick={handleSubmit} className="primary-button">
          确定
        </Button>
      </View>
    </PopupProvider>
  );
};

export default RecordAdd;
